/**
 * @file     addStrings.js
 * @brief    [415. 字符串相加](https://leetcode.cn/problems/add-strings/description/)
 * @author   Zhu
 * @date     2023-02-13 00:02
 */

/**
 * 支持负号
 * @param {string} num1
 * @param {string} num2
 * @return {string}
 */
var addStrings = function (num1, num2) {
    let neg1 = false,
        neg2 = false;
    if (num1.startsWith('-')) {
        num1 = num1.slice(1);
        neg1 = true;
    }
    if (num2.startsWith('-')) {
        num2 = num2.slice(1);
        neg2 = true;
    }

    // remove starts zeroes
    num1 = num1.replace(/^0+(?=0$|[^0])/, '');
    num2 = num2.replace(/^0+(?=0$|[^0])/, '');

    const len1 = num1.length;
    const len2 = num2.length;
    const maxLength = Math.max(len1, len2);

    let sign = '';
    let operators = [1, 1];
    if (neg1 && neg2) {
        sign = '-';
        operators = [1, 1];
    } else if (neg1 || neg2) {
        if (len1 > len2) {
            if (neg1) sign = '-';
            operators = [1, -1];
        } else if (len1 < len2) {
            if (neg2) sign = '-';
            operators = [-1, 1];
        } else {
            if (num1 > num2) {
                if (neg1) sign = '-';
                operators = [1, -1];
            } else if (num1 < num2) {
                if (neg2) sign = '-';
                operators = [-1, 1];
            } else {
                return '0';
            }
        }
    }

    let total = '';
    let carry = 0;
    for (let i = 0; i < maxLength; i++) {
        const sum =
            carry +
            +(num1[len1 - i - 1] ?? 0) * operators[0] +
            +(num2[len2 - 1 - i] ?? 0) * operators[1];

        if (sum < 0) {
            total = sum + 10 + total;
            carry = -1;
        } else if (sum < 10) {
            total = sum + total;
            carry = 0;
        } else {
            total = sum - 10 + total;
            carry = 1;
        }
    }

    if (carry > 0) {
        total = '1' + total;
    }

    total = total.replace(/^0+(?=0$|[^0])/, '');

    return sign + total;
};
